package com.w.utils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author Administrator
 * @Date 2020/12/7 11:43
 */
public class MybatisUtils {
    //声明SqlSessionFactory对象
    public static SqlSessionFactory sqlSessionFactory;
    public static SqlSession sqlSession;
    static {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        sqlSessionFactory = (SqlSessionFactory) applicationContext.getBean("sqlSessionFactory");
    }
    /**
     * 获取到SqlSession，如果传入boolean类型就回设置是否提交事务
     * */
    public static  SqlSession getSqlSession(){
       return sqlSession= sqlSessionFactory.openSession();
    }
    public static SqlSession getSqlSession(Boolean bool){
        return sqlSession= sqlSessionFactory.openSession(bool);
    }

    /**
     * 获取到getMapper对象
     * */
    public static Object getMapper(Class cla,boolean bool){
        return getSqlSession(bool).getMapper(cla);
    }

    public static Object getMapper(Class cla){
        return getSqlSession().getMapper(cla);
    }

    /**
     * 关闭sqlSession
     * */
    public static void closeSqlSession(){
        if(sqlSession!=null){
            sqlSession.close();
        }else {
            sqlSession.close();
        }
    }

}
